export const initState = {
    shopNum: 0,
    cartNum: 0,
    totalPrice: 0,
    list: []
}

export const actions = {
    addCart: (payload) => ({ type: 'ADD_CART', payload }),
    changeCount: (payload) => ({ type: 'CHANGE_COUNT', payload }),
    inputCount: (payload) => ({ type: 'INPUT_COUNT', payload })
}

export function reducer (state=initState, { type, payload }) {
    const newState = JSON.parse(JSON.stringify(state))
    switch(type) {
        case 'ADD_CART':
            addCartFn(newState, payload);
            break;
        case 'CHANGE_COUNT':
            changeCountFn(newState, payload);
            break;
        case 'INPUT_COUNT':
            inputCountFn(newState, payload);
            break;
        default:
            return newState
    }
    return newState
}

function addCartFn (state, shop) {
    state.totalPrice += Number(shop.price);
    state.shopNum++;
    const flag = state.list.some(item => item.id === shop.id);
    if (!flag) {
        shop.count = 1;
        state.list.push(shop);
        state.cartNum++;
    } else {
        state.list.map(item => {
            if (item.id !== shop.id) return item;
            item.count++;
            return item;
        })
    }
}

function changeCountFn (state, info) {
    state.shopNum += info.num;
    const shop = state.list.filter(item => item.id === info.id)[0];
    state.totalPrice += Number(shop.price) * info.num;
    if (shop.count + info.num === 0) {
        state.list = state.list.filter(item => item.id !== info.id);
        state.cartNum--;
    } else {
        state.list.map(item => {
            if (item.id !== info.id) return item;
            item.count += info.num;
            return item;
        })
    }
}

function inputCountFn (state, info) {
    const shop = state.list.filter(item => item.id === info.id)[0];
    if (shop.count > info.num) {
        const num = shop.count - info.num;
        state.shopNum -= num;
        state.totalPrice -= Number(shop.price) * num;
    } else {
        const num = info.num - shop.count;
        state.shopNum += num;
        state.totalPrice += Number(shop.price) * num;
    }
    state.list.map(item => {
        if (item.id !== info.id) return item;
        item.count = info.num;
        return item;
    })
}